package io.task.cc.network.utils.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;


/**
 * @author huihui
 */
public class LockedList<T> extends LockedObject<List<T>> {
    private static final Logger log = LoggerFactory.getLogger(LockedList.class);


    public LockedList(List<T> list) {
        super(list);
    }


    public boolean add(T t) {
        WriteLock writeLock = this.writeLock();
        writeLock.lock();
        try {
            List<T> list = this.getT();
            return list.add(t);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
        return false;
    }

    public int size() {
        ReadLock readLock = this.readLock();
        readLock.lock();
        try {
            List<T> list = this.getT();
            return list.size();
        } finally {
            readLock.unlock();
        }
    }

    public boolean remove(T t) {
        WriteLock writeLock = this.writeLock();
        writeLock.lock();
        try {
            List<T> list = this.getT();
            return list.remove(t);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
        return false;
    }

    public void clear() {
        WriteLock writeLock = this.writeLock();
        writeLock.lock();
        try {
            List<T> list = this.getT();
            list.clear();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        } finally {
            writeLock.unlock();
        }
    }

}
